package br.com.quad.dao;

import java.util.List;

import br.com.quad.bean.Cor;
import br.com.quad.dao.HibernateDAOFactory;

public class CorDAOHibernate implements CorDAO {

	
	HibernateDAOFactory hibernateDAOFactory = null;
	HibernateDAO<Cor> hibernateDAO = null;
	
	public CorDAOHibernate() {
		hibernateDAOFactory = new HibernateDAOFactory();
		hibernateDAO = hibernateDAOFactory.getCorDAO();
	}
	
	
	@Override
	public boolean inserir(Cor cor) throws Exception {
		boolean ok = false;

		try {
			hibernateDAO.add(cor);
			ok = true;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} 
		return ok;
	}
	
	@Override
	public boolean alterar(Cor cor) throws Exception {
		boolean ok = false;

		try {
			hibernateDAO.update(cor);
			ok = true;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}

		return ok;
	}

	@Override
	public boolean excluir(Cor cor) throws Exception {
		boolean ok = false;

		try {
			hibernateDAO.remove(cor);
			ok = true;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} 

		return ok;
	}

	@Override
	public Cor getCor(int codigoCor) {
		return hibernateDAO.get(codigoCor);
	}
	
	@Override
	public List<Cor> getListarTodos() {
		return hibernateDAO.listAll();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Cor> getSelecionar(String descricao) {
		String 	sql = "FROM Cor WHERE codigoCor <> 0";

		if (!(descricao.isEmpty())) {
			sql += " AND descricao like '" + descricao + "%' ";  
		}
		
		sql += " ORDER BY descricao";		
 
		List<Cor> lista = hibernateDAO.getSession().createQuery(sql).list();
		
		return lista;
	}

	@Override
	public boolean isExclusaoLiberada(Cor cor) {
		// TODO Auto-generated method stub
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean isExiste(Cor cor) {
			String 	sql = 	" FROM Cor " +
					"WHERE descricao	= '"+ cor.getDescricao() + "' AND " +
					"		codigoCor != '" + cor.getCodigoCor() + "'";

			List<Cor> lista = hibernateDAO.getSession().createQuery(sql).list();
		    
			if (lista.size()<1) {
				return false;
			} else {
				return true;
			}
	}

}
